var orgId = 1;
var countdown = 60; //计时60s
var countTimer;
var org = [];
var parentOrg = [];
layui.use(['table', 'form', 'laydate'], function() {
	var table = layui.table,
		$ = layui.jquery,
		layer = layui.layer,
		form = layui.form,
		laydate = layui.laydate;

	//复选框样式
	ckBoxColor();
	//初始化查询参数
	var options = {
		offset: 0,
		limit: 30,
		pageIndex: 1,
	};
	var tempOptions = options;
	/**初始化部门**/
	initOrigin();
	loadData(options);
	$(document).keyup(function(event){
		if(event.keyCode ==13){
			$(".searchTools .search-btn").trigger("click");
		}
	});
	//查询
	$(".searchTools .search-btn").on("click", function() {
		var originName = $.trim($(".searchTools .originName").val());
		var type = $.trim($(".searchTools .type").val());
		var datas = {
			offset: 0,
			limit: 30,
			pageIndex: 1
		};
		if(!isNull(originName))
			datas['originName'] = originName;
		if(!isNull(type) && type != -1)
			datas['type'] = type;

		tempOptions = datas;
		loadData(datas);
	});

	/**同步OA部门**/
	$(".searchTools .syn-origin-btn").on("click", function () {
		var loading = layer.load(1);
		$.ajax({
			type: "POST",
			url: "/sys_origin/syn/origin",
			async: true,
			dataType: 'json',
			timeout: 5000,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				layer.msg(res.msg);
				loadData(tempOptions);
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	});

	//点击添加
	$(".searchTools .add-btn").on("click", function() {
		$(".addModal").show();
	})

	//点击关联菜单
	$(".originList").on("click", ".concat-btn", function() {
		$(".concatModal").show();

		var options = {orgId: parseInt($(this).attr('data-id'))};
		$('.concatModal .originAndMenuTitle').html($(this).attr('data-originName') + '==>关联菜单列表');
        orgId = parseInt($(this).attr('data-id'));
		loadMenu(options);
	});

	/**关闭关联部门弹出框**/
	$(".concatModal .close").on("click", function() {
		$(".concatModal").hide();
	});

	//删除关联
	$(".concatModal").on("click", ".btn-delConcat", function() {
        var mid = $(this).attr("data-id");
        var orgId = $(this).attr('data-orgId');
        var options = {mid: parseInt(mid), orgId: parseInt(orgId)};
		var url = '/sys_origin/delete/relation/' + orgId;
		updateOrigin(options, url, 0);
	});

	//添加关联
	$(".concatModal").on("click", ".btn-addConcat", function() {
		var mid = $(this).attr("data-id");
		var orgId = $(this).attr('data-orgId');
		var options = {mid: parseInt(mid), orgId: parseInt(orgId)};
		var url = '/sys_origin/add/relation/' + orgId;
		updateOrigin(options, url, 0);
	});

	//点击禁用
	$(".originList").on("click", ".del-btn", function() {
		var options = {
			id: parseInt($(this).attr('data-id')),
			status: 1
		};
		updateOrigin(options, "/sys_origin/update/status/" + parseInt($(this).attr('data-id')), 1);
	});
	//点击启用
	$(".originList").on("click", ".on-btn", function() {
		var options = {
			id: parseInt($(this).attr('data-id')),
			status: 0
		};
		updateOrigin(options, "/sys_origin/update/status/" + parseInt($(this).attr('data-id')), 1);
	});

	$(".addModal .close").on("click", function() {
		$(".addModal").hide();
		$(".addModal input").val("");
		$(".addModal select").val("");
		$(".addModal textarea").val("");
		form.render();
	})
	//点击添加提交
	form.on('submit(addBtns)', function() {
		var fullName = $.trim($(".addModal .fullName").val());
		var originName = $.trim($(".addModal .originName").val());
		var wxOrgId = $.trim($(".addModal .wxOrgId").val());
		var type = $.trim($(".addModal .type").val());
		var orgCode = $.trim($(".addModal .orgCode").val());
		var sortby = $.trim($(".addModal .sortby").val());
		var pid = -1;

		if(isNull(originName)) {
			layer.msg("请输入部门名称！");
			return;
		}
		var options = {
			orgCode: orgCode,
			pid: pid,
			originName: originName,
			fullName: fullName,
			wxOrgId: wxOrgId,
			sortby: sortby,
			type: type
		};
		//		console.log(options);
		var loading = layer.load(1);
		$.ajax({
			type: "put",
			url: "/sys_origin/save",
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				if(res.code == 0) {
					layer.msg(res.msg);
					$(".addModal").hide();
					$(".addModal input").val("");
					$(".addModal select").val("");
					$(".addModal textarea").val("");
					form.render();
					loadData(tempOptions);
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	})
	//修改按钮
	$(".originList").on("click", ".set-btn", function() {
		$(".updateModal").show();
		orgId = $(this).attr('data-id');
		$(".updateModal .pid").val($(this).attr("data-pid"));
		$(".updateModal .originName").val($(this).attr("data-originName"));
		$(".updateModal .fullName").val($(this).attr("data-fullName"));
		$(".updateModal .type").val($(this).attr("data-type"));
		$(".updateModal .orgCode").val($(this).attr("data-orgCode"));
		$(".updateModal .sortby").val($(this).attr("data-sortby"));
		$(".updateModal .wxOrgId").val($(this).attr("data-wxOrgId"));
		form.render();
	})
	$(".updateModal .close").on("click", function() {
		$(".updateModal").hide();
		$(".updateModal input").val("");
		$(".updateModal select").val("");
		$(".updateModal textarea").val("");
		form.render();
		$("body .ckBox").removeClass("on");
	})
	//部门修改
	form.on('submit(updateBtns)', function() {
		var id = orgId;
		var pid = $.trim($(".updateModal .pid").val());
		var orgCode = $.trim($(".updateModal .orgCode").val());
		var originName = $.trim($(".updateModal .originName").val());
		var type = $.trim($(".updateModal .type").val());
		var fullName = $.trim($(".updateModal .fullName").val());
		var wxOrgId = $.trim($(".updateModal .wxOrgId").val());
		var sortby = $.trim($(".updateModal .sortby").val());
		if(originName == '' || originName == null || originName == undefined) {
			layer.msg("请输入部门名称！");
			return;
		}

		var options = {
			id: parseInt(id),
			originName: originName
		};
		if (pid != null && pid != undefined && pid != '')
			options['pid'] = parseInt(pid);

		if (orgCode != null && orgCode != undefined && orgCode != '')
			options['orgCode'] = orgCode;

		if(wxOrgId != null && wxOrgId != undefined && wxOrgId != "")
			options['wxOrgId'] = wxOrgId;

		if(fullName != null && fullName != undefined && fullName != "")
			options['fullName'] = fullName;

		if(type != null && type != undefined && type != "")
			options['type'] = type;

		if(sortby != null && sortby != undefined && sortby != "")
			options['sortby'] = sortby;

		var loading = layer.load(1);
		$.ajax({
			type: "put",
			url: "/sys_origin/update/" + id,
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				if(res.code == 0) {
					layer.msg(res.msg);
					$(".updateModal").hide();
					$(".updateModal input").val("");
					$(".updateModal select").val("");
					$(".updateModal textarea").val("");
					form.render();
					loadData(tempOptions);
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	})

	//获取数据列表
	function loadData(options) {
		var loading = layer.load(1);
		$.ajax({
			type: "POST",
			url: "/sys_origin/list",
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
								// console.log(res);
				if(res.code == 0) {
					$(".originListPage").page({
						total: res.data.total, //总条数
						pageIndex: options.pageIndex, //当前页
						pageSize: options.limit, //每页显示
						showInfo: true, //是否显示记录信息
						prevBtnText: '上一页',
						nextBtnText: "下一页",
						infoFormat: '总共{total}条记录,每页显示{size}条记录,共{count}页' //定义记录信息格式
					}).on("pageClicked", function(event, pageIndex) {
						//分页点击
						options.offset = options.offset - (options.pageIndex-pageIndex )* options.limit;
						options.pageIndex = pageIndex;
						loadData(options);
					});

					//具体数据列表
					var data = res.data.records;
					if(data == null || data.length <= 0) {
						$(".originList .tableList").empty().append("<tr><td colspan='9'>暂无数据</td></tr>");
						return;
					}
					var html = '';
					$.each(data, function(index, val) {
						var typeStr = '工厂';
						var statusStr = '启用';
						var statusBtn = '';
						if (val.status == 0)
							statusStr = '启用';
						else
							statusStr = '禁用';

						if (val.type == 0)
							typeStr = '集团公司'
						else if (val.type == 1)
							typeStr = '部门';
						else
							typeStr = '工厂';

						if (val.status == 0)
							statusBtn = '<a href="javascript:void(0)" data-id="' + val.id + '" class="layui-btn del-btn" style="background-color:#d9534f"><img src="/static/console/img/off.png" />禁用</a>';
						else
							statusBtn = '<a href="javascript:void(0)" data-id="' + val.id + '" class="layui-btn on-btn" style="background-color:#5FB878"><img src="/static/console/img/on.png" />启用</a>';


						// var concatBtn = '<a href="javascript:void(0)" data-originName="' + val.originName + '" data-id="' + val.id + '" class="layui-btn concat-btn" style="background-color:#61C3A2"><img src="/static/console/img/concat.png" />关联菜单</a>';
						var btn = '<a href="javascript:void(0)" data-wxOrgId="' + val.wxOrgId + '" data-sortby="' + val.sortby + '" data-orgCode="' + val.orgCode
							+ '" data-type="' + val.type + '" data-fullName="' + convertVal(val.fullName) + '" data-originName="' + convertVal(val.originName)
							+ '" data-pid="' + val.pid + '" data-id="' + val.id + '" class="layui-btn set-btn" ' +
							'style="background-color:#1890ff"><img src="/static/console/img/edit.png" />修改</a>' + statusBtn ;


						html += "<tr><td>" + val.id + "</td><td>" + convertVal(val.originName) + "</td>" +
							"<td data-type='" + val.type + "'>" + typeStr + "</td><td>" + convertOrigin(val.pid, val.type) + "</td><td>" + convertVal(val.fullName) + "</td><td data-status='" + val.status + "'>" + statusStr + "</td><td>"
							+ val.orgCode + "</td><td>" + val.sortby + "</td><td>" + convertVal(val.wxOrgId) + "</td><td>" + btn + "</td></tr>";
					});
					$(".originList .tableList").empty().append(html);
					replaceNull($(".originList .tableList"));
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});

	}


	/**显示值转换**/
	function convertVal(val) {
		if (val == null || val == '' || val == undefined)
			return '';
		else
			return val;
	}

	/***初始化部门信息***/
	function initOrigin() {
		$.ajax({
			type: "post",
			url: '/sys_origin/query/origin',
			async: true,
			dataType: 'json',
			timeout: 5000,
			// data: options,
			success: function(res) {
				if(res.code == 0) {
					$.each(res.data, function(index, val) {
						parentOrg[val.id] = val.pid;
						org[val.id] = val.originName;
					});
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					return;
				}
			}
		});
	}

	/**转换部门名称**/
	function convertOrigin(id, type) {
		var orgName = '';
		if (type == 1) {
		   var pid = parentOrg[id];
		   orgName = convertVal(org[id]);
		   if (orgName != null && orgName != undefined && orgName != '')
			   if (org[pid] != null && org[pid] != undefined && org[pid] != '')
		   			orgName = org[pid] + ' ==> ' + orgName;
		   else
				orgName = convertVal(org[pid]);
		} else {
		   orgName = convertVal(org[id]);
		}
		return orgName;
	}

	/**加载菜单信息**/
	function loadMenu(options) {
		var loading = layer.load(1);
		$.ajax({
			type: "post",
			url: '/sys_origin/query/menu',
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				if(res.code == 0) {
					if($(".updateModal").show()){
						$(".updateModal").hide();
						$(".updateModal input").val("");
					}
					var data = res.data;
					loadMenuData(data);
				} else {
					layer.msg(res.msg);
					return;;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}

	/**组装菜单信息数据**/
	function loadMenuData(data) {
		if(data == null || data.length <= 0) {
			$(".concatModal .originAndMenuList .tableList").empty().append("<tr><td colspan='4'>暂无数据</td></tr>");
			return;
		}
		var html = '';
		$.each(data, function(index, val) {
			var statusText = "";
			var btn = "";
			var name = val.name;
			if (val.type == 0)
				name = name + '(手机)';
			else if (val.type == 1)
				name = name + '(后台)';
			if (val.status == 0) {
				statusText = '已关联';
				btn = "<a href='javascript:void(0)' data-orgId='" + orgId + "' data-id='" + val.id + "' class='layui-btn btn-delConcat'>删除关联</a>";
			} else {
				btn = "<a href='javascript:void(0)' data-orgId='" + orgId + "' data-id='" + val.id + "' class='layui-btn btn-addConcat'>添加关联</a>";
			}
			html += "<tr><td>" + name +
				"</td><td>" + statusText + "</td><td>" + btn + "</td></tr>";
		});
		$(".concatModal .originAndMenuList .tableList").empty().append(html);
		replaceNull($(".concatModal .originAndMenuList .tableList"));
	}

	/**关联操作**/
	function updateOrigin(options, url, type) {
		var loading = layer.load(1);
		$.ajax({
			type: "put",
			url: url,
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				if(res.code == 0) {
					layer.msg(res.msg);
					if (type == 0)
						loadMenu(options);
					else if (type == 1)
						loadData(tempOptions);
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}
	
});